<template>
  <view class="container">
    <view class="empty-cart" v-if="cartList.length === 0">
      <image
        src="/static/cart-icons/empty-cart.png"
        mode="aspectFit"
        class="empty-image"
      />
      <text class="empty-text">购物车还是空的</text>
      <button class="go-shopping" @tap="goShopping">去逛逛</button>
    </view>

    <view class="cart-content" v-else>
      <view class="cart-header">
        <view class="store-info">
          <uni-icons type="shop" size="24" color="#333"></uni-icons>
          <text class="store-name">大米哥的店</text>
        </view>
        <text class="edit-btn" @tap="toggleEdit">{{
          isEdit ? "完成" : "编辑"
        }}</text>
      </view>

      <view class="cart-list">
        <view class="cart-item" v-for="(item, index) in cartList" :key="index">
          <view class="checkbox">
            <checkbox
              :checked="item.selected"
              @tap="handleSelect(item)"
              style="transform: scale(0.8)"
            />
          </view>
          <image
            :src="item.primaryImage"
            mode="aspectFill"
            class="goods-image"
          />
          <view class="goods-info">
            <text class="goods-name">{{ item.title }}</text>
            <text class="goods-specs">{{ item.specs }}</text>
            <view class="price-box">
              <text class="price">¥{{ item.salePrice }}</text>
              <view class="quantity-box">
                <text class="minus" @tap="updateQuantity(item, index, -1)"
                  >-</text
                >
                <input
                  type="number"
                  v-model="item.quantity"
                  class="quantity-input"
                  @blur="handleQuantityBlur(item, index)"
                />
                <text class="plus" @tap="updateQuantity(item, index, 1)"
                  >+</text
                >
              </view>
            </view>
          </view>
        </view>
      </view>

      <view class="settlement-bar">
        <view class="select-all">
          <checkbox
            :checked="isAllSelected"
            @tap="handleSelectAll"
            style="transform: scale(0.8)"
          />
          <text>全选</text>
        </view>
        <view class="total-box" v-if="!isEdit">
          <view class="price-info">
            <text>合计：</text>
            <text class="total-price">¥{{ totalPrice }}</text>
          </view>
          <button
            class="settlement-btn"
            :disabled="!selectedCount"
            @tap="settlement"
          >
            结算({{ selectedCount }})
          </button>
        </view>
        <view class="delete-box" v-else>
          <button
            class="delete-btn"
            :disabled="!selectedCount"
            @tap="deleteSelected"
          >
            删除({{ selectedCount }})
          </button>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { onShow } from "@dcloudio/uni-app";
import { useCartStore } from "@/store/cartStore";
import { useUserStore } from "@/store/userStore";
import { storeToRefs } from "pinia";
import { checkLoginAndRedirect, getToken } from "@/utils/auth";

// 初始化 store
const cartStore = useCartStore();
const userStore = useUserStore();

// 从 store 中解构数据
const { cartList, isEdit, isAllSelected, selectedCount, totalPrice } =
  storeToRefs(cartStore);

// 从 store 中解构方法
const { 
  updateQuantity: storeUpdateQuantity,
  handleQuantityInput,
  setItemSelected,
  setAllSelected,
  toggleEdit,
  deleteSelected,
  settlement
} = cartStore;

// 跳转到分类页面
const goShopping = () => {
  uni.switchTab({
    url: "/pages/category/category",
  });
};

// 更新商品数量
const updateQuantity = (item, index, delta) => {
  storeUpdateQuantity(index, delta);
};

// 处理数量输入框失焦
const handleQuantityBlur = (item, index) => {
  handleQuantityInput(index, item.quantity);
};

// 处理选择商品
const handleSelect = (item) => {
  const index = cartList.value.indexOf(item);
  setItemSelected(index, !item.selected);
};

// 处理全选
const handleSelectAll = () => {
  setAllSelected(!isAllSelected.value);
};

// 生命周期钩子：页面显示时加载购物车数据
onShow(async () => {
  try {
    // 检查登录状态
    const token = getToken();
    console.log('当前token:', token);

    if (!token) {
      console.log('未检测到token');
      uni.navigateTo({
        url: "/pages/login/login",
      });
      return;
    }

    // 获取用户信息
    const userInfo = await userStore.getUserInfo();
    console.log('当前用户信息:', userInfo);

    if (!userInfo) {
      console.log('获取用户信息失败');
      uni.removeStorageSync("token");
      uni.navigateTo({
        url: "/pages/login/login",
      });
      return;
    }

    console.log('开始调用loadCartData');
    // 加载购物车数据
    await cartStore.loadCartData();
    console.log('loadCartData调用完成');
    
  } catch (error) {
    console.error("购物车页面错误:", error);
    // 打印完整的错误信息
    console.error("错误详情:", {
      message: error.message,
      stack: error.stack
    });

    if (error.message.includes("未登录") || error.message.includes("token")) {
      uni.navigateTo({
        url: "/pages/login/login",
      });
    } else {
      uni.showToast({
        title: "加载购物车失败",
        icon: "none",
      });
    }
  }
});
</script>

<style lang="scss">
.container {
  min-height: 100vh;
  background-color: #f8f8f8;
  padding-bottom: 100rpx;
}

.empty-cart {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding-top: 200rpx;

  .empty-image {
    width: 240rpx;
    height: 240rpx;
    margin-bottom: 30rpx;
  }

  .empty-text {
    font-size: 28rpx;
    color: #999;
    margin-bottom: 40rpx;
  }

  .go-shopping {
    width: 240rpx;
    height: 80rpx;
    line-height: 80rpx;
    text-align: center;
    background-color: #ff4444;
    color: #fff;
    border-radius: 40rpx;
    font-size: 28rpx;
  }
}

.cart-content {
  .cart-list {
    background-color: #fff;
    overflow: hidden;

    .cart-item {
      display: flex;
      align-items: center;
      padding: 20rpx;
      border-bottom: 2rpx solid #f5f5f5;

      .checkbox {
        margin-right: 20rpx;
        display: flex;
        align-items: center;
      }

      .goods-image {
        width: 160rpx;
        height: 160rpx;
        border-radius: 8rpx;
      }

      .goods-info {
        flex: 1;
        margin-left: 20rpx;

        .goods-name {
          font-size: 28rpx;
          color: #333;
          line-height: 1.4;
          margin-bottom: 20rpx;
        }

        .goods-specs {
          font-size: 24rpx;
          color: #999;
          margin-bottom: 16rpx;
        }

        .price-box {
          display: flex;
          justify-content: space-between;
          align-items: center;

          .price {
            font-size: 32rpx;
            color: #ff4444;
            font-weight: bold;
          }

          .quantity-box {
            display: flex;
            align-items: center;

            .minus,
            .plus {
              width: 60rpx;
              height: 60rpx;
              line-height: 60rpx;
              text-align: center;
              background-color: #f5f5f5;
              color: #333;
            }

            .quantity-input {
              width: 80rpx;
              height: 60rpx;
              text-align: center;
              background-color: #f5f5f5;
              margin: 0 4rpx;
            }
          }
        }
      }
    }
  }
}

.settlement-bar {
  position: fixed;
  left: 0;
  bottom: 0;
  width: 100%;
  height: 100rpx;
  background-color: #fff;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 30rpx;
  box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
  z-index: 999;
  border-top: 2rpx solid #f5f5f5;
  background: linear-gradient(
    to bottom,
    rgba(255, 255, 255, 0.95) 0%,
    #ffffff 20%
  );

  .select-all {
    display: flex;
    align-items: center;

    text {
      font-size: 28rpx;
      color: #333;
      margin-left: 10rpx;
    }
  }

  .total-box {
    display: flex;
    align-items: center;

    .price-info {
      margin-right: 20rpx;

      .total-price {
        font-size: 36rpx;
        color: #ff4444;
        font-weight: bold;
      }
    }

    .settlement-btn {
      width: 200rpx;
      height: 80rpx;
      line-height: 80rpx;
      text-align: center;
      background-color: #ff4444;
      color: #fff;
      border-radius: 40rpx;
      font-size: 28rpx;

      &:disabled {
        background-color: #ccc;
      }
    }
  }
}

.cart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx 30rpx;
  background-color: #fff;
  margin-bottom: 20rpx;

  .store-info {
    display: flex;
    align-items: center;

    .shop-icon {
      width: 40rpx;
      height: 40rpx;
      margin-right: 10rpx;
    }

    .store-name {
      font-size: 28rpx;
      color: #333;
      margin-left: 10rpx;
    }
  }

  .edit-btn {
    font-size: 28rpx;
    color: #666;
    padding: 10rpx;
  }
}

.delete-box {
  .delete-btn {
    width: 200rpx;
    height: 80rpx;
    line-height: 80rpx;
    text-align: center;
    background-color: #ff4444;
    color: #fff;
    border-radius: 40rpx;
    font-size: 28rpx;

    &:disabled {
      background-color: #ccc;
    }
  }
}
</style>
